#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os, sys
import zipfile

DEFAULT_TIMEOUT = 15
DEFAULT_TAR_BALL = 'pwpd_cert_v1.0.zip'

def _unzip_exec(exec_zip, target_dir = ''):
    exec_zip = os.path.expanduser(exec_zip)    
    # default extract target directory.
    if not target_dir:
        target_dir = os.path.splitext(exec_zip)[0]
    
    zip_f = zipfile.ZipFile(exec_zip, 'r')
    for k in zip_f.infolist():
        save_path = os.path.join(target_dir, k.filename)
        save_dir = os.path.dirname(save_path)
        # empty directory in archive.
        if save_path.endswith(os.sep):
            if not os.path.exists(save_path):
                os.makedirs(save_path)
        # general file in archive.
        else:
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            #
            f = open(save_path, 'wb')
            f.write(zip_f.read(k))
            f.close()
    #
    zip_f.close()
    return target_dir

def extract_exec(archive_dir):
    exec_fn = os.path.join(archive_dir, DEFAULT_TAR_BALL)
    exec_dir = os.path.join(_unzip_exec(exec_fn), 'src')
    
    return exec_dir

def do_main(argv):
    
    from pwpd.common import config
    from pwpd.core import pwdlogging
    from pwpd.core import pwdcore
    
    s_fname = sys.argv[0]
    exec_dir = sys.argv[1]

    param_fname = sys.argv[2]
    taskid = sys.argv[3]
    ret_addr = sys.argv[4]
    
    config_file = os.path.join(exec_dir, 'etc', 'pwpd_cert.conf')
    cfg = config.load_config(config_file, exec_dir)
    
#    logfile = os.path.join(exec_dir, cfg.get_opt(config.OPT_LOGDIR), 'pwpd.log')
    logfile = os.path.join(exec_dir, cfg.get_opt(config.OPT_LOGDIR), taskid + '_pwpd.log')
    logger = pwdlogging.get_logger("pwd.daemon.cmdmain", logfile , default = True)
    
    TT_Start = time.time()
    
    runner = pwdcore.PWPDRunner(cfg, DEFAULT_TIMEOUT, ret_addr, param_fname, taskid)
    runner.detecting_start()
    
    runner.dump_reuslt('FTP', ret_addr)
#    print >> sys.stdout, runner.zip_output()
    
    TT_elapse = time.time() - TT_Start
    
    logger.info("############### time elapse: %f", TT_elapse)
    print >> sys.stdout, '=====>>>>> completed! Clock elapse: %f' % TT_elapse
    
if __name__ == '__main__':
    
    #
    # bootstrap.py [DIRECTORY of exec. zip] [param file] [taskID] [ret. address]
    #     e.g., bootstrap.py ~/tmp/ ~/tmp/slice_dns_20130730.data task-001 ftp:////0.0.0.0
    
    s_fname = sys.argv[0]
#    exec_dir = sys.argv[1]
    exec_dir = extract_exec(sys.argv[1])
    sys.argv[1] = exec_dir
    #
    sys.path.append(exec_dir)
    do_main(sys.argv)